package com.songtech.uitest.util;

import com.songtech.uitest.aspects.LogAspect;
import com.songtech.uitest.components.ScreenShoter;
import com.songtech.uitest.entities.Indent;
import org.apache.commons.lang3.StringUtils;
import org.openqa.selenium.WebDriver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.testng.Assert;

import java.util.ArrayList;
import java.util.List;

/**
 * 为了避免测试方法一旦遇到断言失败就停止继续运行，特加此类
 */
public class Assertion {

    public static boolean flag = true; //true代表正确，false代表出错

    public static boolean fatal = false; //是否影响主流程，false不影响，true影响

    public static List<Error> errors = new ArrayList<Error>();

    private static Logger logger = LoggerFactory.getLogger(Assertion.class);


    /**
     *
     * @param actual 实际值
     * @param expected 期望值
     * @param fatalOrNot 代表此问题是否影响主流程，若影响则设为true，不影响则设为false
     */
    public static void verifyEquals(Object actual, Object expected, boolean fatalOrNot){
        verifyEquals(actual, expected, fatalOrNot, "无");
    }

    public static void verifyEquals(Object actual, Object expected, boolean fatalOrNot, String message){
        try{
            Assert.assertEquals(actual, expected, message);
            flag = true;
            fatal = false;
        }catch(Error e){
            //错误截图
            ScreenShoter screenShoter = (ScreenShoter) SpringUtil.getBean("screenShoter");
            screenShoter.screenShot("断言");

            //错误记录日志
            //得到当前位置，flow,
            Indent indent = (Indent) SpringUtil.getBean("indent");
            int pos = indent.getStepPosition();
            String flow = indent.getFlow();
            String[] flowArray = flow.split(",");
            ModulesMapper modulesMapper = (ModulesMapper) SpringUtil.getBean("modulesMapper");
            String classMethod = modulesMapper.getClassMethod(flowArray[pos].substring(0, 3));
            //得到类名
            String clsName = StringUtils.substringBefore(classMethod, ".");
            //得到方法名
            String methodName = StringUtils.substringAfterLast(classMethod, ".");
            //日志输出
            String msg="执行" + clsName + "类" + methodName + "方法的断言失败，断言信息：" + message;
            Space space = (Space) SpringUtil.getBean("space");
            logger.error(space.getSpace() + msg);

            //记录到汇总类
            SumUpHelper sumUpHelper = (SumUpHelper) SpringUtil.getBean("sumUpHelper");
            sumUpHelper.getAssertErrorList().add(msg);

            //记录到本类自己的错误list
            errors.add(e);
            flag = false; //代表有错误
            fatal = fatalOrNot; //是否影响主流程

            //如果是致命的，影响流程的错误，则抛出，让TestNG框架自动处理
            if(fatal){
                throw e;

            }

        }
    }
}
